package org.starsource.forum.server.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.starsource.forum.client.exception.DatabaseException;
import org.starsource.forum.client.exception.MessageNotFoundException;
import org.starsource.forum.server.domain.Message;
import org.starsource.forum.server.domain.User;
import org.starsource.forum.server.transaction.MessengerTransaction;
import org.starsource.forum.server.util.Config;
import org.starsource.forum.server.util.Thumbnail;
import org.starsource.forum.shared.util.ImageTypeHelper;

public class FileUploadServlet extends SpringHttpServlet {
	private static org.apache.log4j.Logger logger = org.apache.log4j.LogManager
	.getLogger(FileUploadServlet.class.getName());

	private static final long serialVersionUID = 1950765544946200378L;

	private static final String SUCCESS_MESSAGE = "OK";
//		"{code:'SUCCESS', message: '文件上传成功', resource_id: '%d'}";
	
	private static final String FAILURE_MESSAGE = "文件上传不成功，原因是：%s";
//		"{code:'FAILURE', message: '文件上传不成功', reason: '%s'}";
	
	
	private MessengerTransaction forumTransaction;
	public void setForumTransaction(MessengerTransaction forumTransaction) {
		this.forumTransaction = forumTransaction;
	}
	
	private Config config;
	public void setConfig(Config config) {
		this.config = config;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		String result = null;
//		String json = null;
		try {
			User requester = ((User)request.getSession().getAttribute("User"));
			Message message = forumTransaction.getMessage(requester, new Integer(request.getParameter("messageId")));

			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			String charset = request.getCharacterEncoding();
			if (charset != null) {
			    upload.setHeaderEncoding(charset);
			}
			
			List<FileItem> items = null;
			items = upload.parseRequest(request);
	
			Iterator<FileItem> it = items.iterator();
			while (it.hasNext()) {
				FileItem item = it.next();
				result = processFile(requester, item, message);
			}
		} catch (MessageNotFoundException e) {
			result = String.format(FAILURE_MESSAGE, "消息不存在，可能已被删除");
		} catch (NumberFormatException e) {
			result = String.format(FAILURE_MESSAGE, "页面参数错误，请与维护人员联系");
			logger.error(e.getStackTrace());
		} catch (DatabaseException e) {
			result = String.format(FAILURE_MESSAGE, "数据库异常，请与维护人员联系");
		} catch (FileUploadException e) {
			result = String.format(FAILURE_MESSAGE, "上传路径错误，请与维护人员联系");
			e.printStackTrace();
			logger.warn(e.toString());
		}

		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(result);
	}

	private String getFileName(String filePath) {
		int fromIndex = 0, index;
		while ((index = filePath.indexOf("/", fromIndex)) >= 0) {
			fromIndex = index + 1;
		}
		while ((index = filePath.indexOf("\\", fromIndex)) >= 0) {
			fromIndex = index + 1;
		}
		return filePath.substring(fromIndex);
	}
	private String processFile(User requester, FileItem item, Message message) {
		String result = null;
		try {
			String fileName = getFileName(item.getName());
			String filePath = requester.getDirectory() + File.separator;
			
			File uploadedFile = new File(filePath + fileName);
			item.write(uploadedFile);
			
			String thumbnail = "";
			int width = 0, height = 0;
			if (ImageTypeHelper.isImage(fileName)) {
				thumbnail = java.util.UUID.randomUUID().toString();
				Thumbnail.saveImageAsJpg(filePath + fileName, config.getThumbnailsPath() + File.separator + thumbnail, 170, 170);
				BufferedImage image = ImageIO.read(new File(filePath + fileName));
				width = image.getWidth();
				height = image.getHeight();
			}
			
			forumTransaction.addResource(requester, fileName, thumbnail, width, height, message);
			result = SUCCESS_MESSAGE;
//			result = String.format(SUCCESS_MESSAGE, resource.getId());
		} catch (Exception e) {
			logger.error(e.getStackTrace());
			
			result = String.format(FAILURE_MESSAGE, e.toString());
		}
		return result;
	}
}
